<?php
namespace app\controller;

use think\Request;
use think\facade\Db;
use app\model\Bazaar;

class Xhs extends Common
{

	/**
	 * 查询数据
	 *
	 * @return
	 */
	public function read(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhs:read')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$where = [];
		$limit = $request->param('limit/d', 20);
		$sort = $request->param('sort', 'id', 'trim');
		$order = $request->param('order', 'desc', 'trim');
		array_push( $where, ['companyId', '=', $request->sessInfo['companyId'] ] );
		array_push( $where, ['userType', '=', 10 ] );
		$username = $request->param('username', '', 'trim');
		if($username) {
			array_push( $where, ['username', 'like',  "%{$username}%" ] );
		}
		$bazaarId = $request->param('bazaarId', '', 'trim');
		if($bazaarId) {
			array_push( $where, ['','exp', Db::raw("FIND_IN_SET({$bazaarId}, bazaarId)")] );
		}
		$userStat = $request->param('userStat', '', 'trim');
		if($userStat) {
			array_push( $where, ['userStat', '=',  $userStat ] );
		}

		$query = Db::name('cfg_expand')->where($where)->field('id,username,password,balance,budget,status,cost,userStat,lastDatetime,bazaarId,regionTarget as cookie')->order($sort, $order)->paginate($limit);
		return ['code'=> 0, 'msg'=> '', 'count'=> $query->total(), 'data'=> $query->items(), 'bazaar' => Bazaar::getList($request->sessInfo, 1) ];
	}

	/**
	 * 小红书登录接口
	 *
	 * @return
	 */
	private function getCampaigns($url, $data, $ip, $cookie) {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_POST, true );
		curl_setopt ( $ch, CURLOPT_HEADER, false);
		curl_setopt ( $ch, CURLOPT_POSTFIELDS, $data );
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false);
		curl_setopt ( $ch, CURLOPT_COOKIE, $cookie);
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, [
			'CLIENT-IP: '.$ip,
			'X-FORWARDED-FOR: '.$ip,
			'content-type: application/json;charset=UTF-8',
			'referer: https://pro.xiaohongshu.com/ares/advertising/microapp/unify-search',
			'user-agent: Mozilla/5.0 (Windows NT '. mt_rand(8, 10) .'.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'. mt_rand(10, 90) .'.0.4240.'. mt_rand(10, 90) .' Safari/'.mt_rand(100, 700).'.36',
		]);
		$string = curl_exec ( $ch );
		curl_close ($ch );
		return $string;
	}

	/**
	 * 小红书登录接口
	 *
	 * @return
	 */
	private function getInfo($url, $ip, $cookie) {
		$ch = curl_init ();
		curl_setopt ( $ch, CURLOPT_URL, $url );
		curl_setopt ( $ch, CURLOPT_POST, false );
		curl_setopt ( $ch, CURLOPT_HEADER, false);
		curl_setopt ( $ch, CURLOPT_FOLLOWLOCATION, true);
		curl_setopt ( $ch, CURLOPT_RETURNTRANSFER, true );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYPEER, false );
		curl_setopt ( $ch, CURLOPT_SSL_VERIFYHOST, false );
		curl_setopt ( $ch, CURLOPT_COOKIE, $cookie);
		curl_setopt ( $ch, CURLOPT_HTTPHEADER, [
			'CLIENT-IP: '.$ip,
			'X-FORWARDED-FOR: '.$ip,
			'content-type: application/json;charset=UTF-8',
			'referer: https://pro.xiaohongshu.com/ares/advertising/microapp/unify-search',
			'user-agent: Mozilla/5.0 (Windows NT '. mt_rand(8, 10) .'.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/'. mt_rand(10, 90) .'.0.4240.'. mt_rand(10, 90) .' Safari/'.mt_rand(100, 700).'.36',
		]);
		$string = curl_exec ( $ch );
		curl_close ($ch );
		return $string;
	}

	/**
	 * 获取随机IP地址
	 *
	 * @return
	 */
	private function getRandAddress() {
		$ip_long = [
			['607649792', '608174079'], //36.56.0.0-36.63.255.255
			['1038614528', '1039007743'], //61.232.0.0-61.237.255.255
			['1783627776', '1784676351'], //106.80.0.0-106.95.255.255
			['2035023872', '2035154943'], //121.76.0.0-121.77.255.255
			['2078801920', '2079064063'], //123.232.0.0-123.235.255.255
			['-1950089216', '-1948778497'], //139.196.0.0-139.215.255.255
			['-1425539072', '-1425014785'], //171.8.0.0-171.15.255.255
			['-1236271104', '-1235419137'], //182.80.0.0-182.92.255.255
			['-770113536', '-768606209'], //210.25.0.0-210.47.255.255
			['-569376768', '-564133889'], //222.16.0.0-222.95.255.255
		];
		$rand_key = mt_rand(0, 9);
		return long2ip(mt_rand($ip_long[$rand_key][0], $ip_long[$rand_key][1]));
	}

	/**
	 * 批量更新
	 *
	 * @return
	 */
	public function updateUser(Request $request) {
		$id = $request->param('id', '', 'trim');
		if(empty($id)) {
			return ['code'=>403, 'msg'=>'ID不能为空!'];
		}

		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('id', $id)->where('userType', 10)->find();
		if(!isset($query['id'])) {
			return ['code'=>403, 'msg'=>'非法请求id不存在!'];
		}

		if(empty($query['regionTarget'])) {
			return ['code'=>403, 'msg'=>'Cookie未设置!'];
		}

		$ip = $this->getRandAddress();

		$doResponse = $this->getInfo('https://pro.xiaohongshu.com/api/eros/user/info', $ip, $query['regionTarget']);
		$jsondata = json_decode($doResponse, true);
		if(isset($jsondata['data']['vSellerId'])) {
			$balance = $budget = $cost = 0;
		    $doResponse = $this->getInfo('https://pro.xiaohongshu.com/api/eros/finance/balance?v_seller_id='.$jsondata['data']['vSellerId'], $ip, $query['regionTarget']);
			$jsondata = json_decode($doResponse, true);
			if(isset($jsondata['data']['totalBalance'])){
				$balance = bcdiv($jsondata['data']['totalBalance'], 100, 2);
			}
			if(isset($jsondata['data']['accountBudget'])){
				$budget = bcdiv($jsondata['data']['accountBudget'], 100, 2);
			}
			if(isset($jsondata['data']['dayToSpending'])){
				$cost = bcdiv($jsondata['data']['dayToSpending'], 100, 2);
			}
			Db::name('cfg_expand')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->update([ 'balance' => $balance, 'budget' => $budget, 'cost' => $cost, 'lastDatetime' => date('Y-m-d H:i:s')]);
		} else {
			Db::query( " UPDATE cfg_expand SET `userStat` = '2', `lastDatetime` = NOW() WHERE id = '{$id}'; ");
		}
    return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 更新数据
	 *
	 * @return
	 */
	public function update(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhs:update')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( isset($param['state']) ) {
			$status = $request->param('status', '', 'trim');
			Db::name('cfg_expand')->where('id', $param['state'])
					->where('companyId', $request->sessInfo['companyId'])
					->update([ 'status' => $status]);
			return ['code'=>0, 'msg'=>'操作成功!'];
		}

		$id = $request->param('id', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$cookie = $request->param('cookie', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$username = $request->param('username', '', 'trim');

		if(empty($username)) {
			return ['code'=>403, 'msg'=>'推广账号不能为空!'];
		}

		$userStat = 2;

		$ip = $this->getRandAddress();

		$balance = $budget = $cost = 0;

		if( $cookie ) {
			$doResponse = $this->getInfo('https://pro.xiaohongshu.com/api/eros/user/info', $ip, $cookie);
			$jsondata = json_decode($doResponse, true);
			if(isset($jsondata['data']['vSellerId'])) {
				$doResponse = $this->getInfo('https://pro.xiaohongshu.com/api/eros/finance/balance?v_seller_id='.$jsondata['data']['vSellerId'], $ip, $cookie);
				$jsondata = json_decode($doResponse, true);
				if(isset($jsondata['data']['totalBalance'])){
					$userStat = 1;
					$balance = bcdiv($jsondata['data']['totalBalance'], 100, 2);
				}
				if(isset($jsondata['data']['accountBudget'])){
					$budget = bcdiv($jsondata['data']['accountBudget'], 100, 2);
				}
				if(isset($jsondata['data']['dayToSpending'])){
					$cost = bcdiv($jsondata['data']['dayToSpending'], 100, 2);
				}
			}
		}

		Db::name('cfg_expand')->where('id', $id)->where('companyId', $request->sessInfo['companyId'])->update([ 'username' => $username, 'password' => $password, 'bazaarId' => $bazaarId,
		  'balance' => $balance, 'budget' => $budget, 'cost' => $cost, 'regionTarget' => $cookie, 'userStat' => $userStat, 'lastDatetime' => date('Y-m-d H:i:s') ]);
		return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 创建数据
	 *
	 * @return
	 */
	public function create(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhs:save')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}

		$id = $request->param('id', '', 'trim');
		$bazaarId = $request->param('bazaarId', '', 'trim');
		$cookie = $request->param('cookie', '', 'trim');
		$password = $request->param('password', '', 'trim');
		$username = $request->param('username', '', 'trim');

		if(empty($username)) {
			return ['code'=>403, 'msg'=>'XHS账号不能为空!'];
		}

		$query = Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])
			->where('userType', 10)->where('username', $username)->value('username');
		if(!empty($query)) {
			return ['code'=>403, 'msg'=>'XHS账号已存在!'];
		}

		$userStat = 2;

		$ip = $this->getRandAddress();

		$doResponse = "";
		if($cookie) {
			$doResponse = $this->getCampaigns('https://pro.xiaohongshu.com/api/eros/rtb/campaigns/index', json_encode([
				'start_time'=> date("Y-m-d 00:00:00", strtotime("-1 day")),
				'end_time'=> date("Y-m-d 23:59:59", strtotime("-1 day")),
				'filter_state'=> 6,
				'marketing_target'=> -1,
				'name'=> "",
				'page_index'=> 1,
				'page_size'=> 20,
				'search_column'=>2,
			]), $ip, $cookie);
		}

		$jsondata = json_decode($doResponse, true);
		if(is_array($jsondata)) {
			if(isset($jsondata['data']['aggregation_data'])) {
				// 展现量
				$impression_str = isset($jsondata['data']['aggregation_data']['impression_str']) ? $jsondata['data']['aggregation_data']['impression_str'] : 0;
				// 点击量
				$click_str = isset($jsondata['data']['aggregation_data']['click_str']) ? $jsondata['data']['aggregation_data']['click_str'] : 0;
				// 消费
				$spent_str = isset($jsondata['data']['aggregation_data']['spent_str']) ? $jsondata['data']['aggregation_data']['spent_str'] : 0;
				// 点击率
				$ctr_str = isset($jsondata['data']['aggregation_data']['ctr_str']) ? rtrim($jsondata['data']['aggregation_data']['ctr_str'], '%') : 0;
				// 平均点击价
				$acp_str = isset($jsondata['data']['aggregation_data']['acp_str']) ? $jsondata['data']['aggregation_data']['acp_str'] : 0;
				// 今天的数据
				$datetime = date("Y-m-d 01:00:00");
				$res = Db::query("select id from cfg_xhs where `companyId` = '{$request->sessInfo['companyId']}' AND `username` = '{$username}' AND to_days(`datetime`) = to_days('{$datetime}') LIMIT 1");
				if( isset($res[0]['id']) ) {
					Db::query( " UPDATE cfg_xhs SET `spent_str` = '{$spent_str}', `bazaarId` = '{$bazaarId}', `impression_str` = '{$impression_str}',
					`click_str` = '{$click_str}', `ctr_str` = '{$ctr_str}', `acp_str` = '{$acp_str}', `update` = NOW() WHERE id = '{$res[0]['id']}'; ");
				} else {
					Db::query("INSERT INTO cfg_xhs ( `companyId`, `username`, `bazaarId`, `spent_str`, `impression_str`, `click_str`, `ctr_str`, `acp_str`, `datetime`, `update` ) values
						( '{$request->sessInfo['companyId']}', '{$username}', '{$bazaarId}', '{$spent_str}', '{$impression_str}', '{$click_str}', '{$ctr_str}', '{$acp_str}', '{$datetime}', NOW() ) " );
				}
			}
		}

		$balance = $budget = $cost = 0;

		if( $cookie ) {
			$doResponse = $this->getInfo('https://pro.xiaohongshu.com/api/eros/user/info', $ip, $cookie);
			$jsondata = json_decode($doResponse, true);
			if(isset($jsondata['data']['vSellerId'])) {
				$doResponse = $this->getInfo('https://pro.xiaohongshu.com/api/eros/finance/balance?v_seller_id='.$jsondata['data']['vSellerId'], $ip, $cookie);
				$jsondata = json_decode($doResponse, true);
				if(isset($jsondata['data']['totalBalance'])) {
					$userStat = 1;
					$balance = bcdiv($jsondata['data']['totalBalance'], 100, 2);
				}
				if(isset($jsondata['data']['accountBudget'])){
					$budget = bcdiv($jsondata['data']['accountBudget'], 100, 2);
				}
				if(isset($jsondata['data']['dayToSpending'])){
					$cost = bcdiv($jsondata['data']['dayToSpending'], 100, 2);
				}
			}
		}

		Db::name('cfg_expand')->insert([ 'companyId' => $request->sessInfo['companyId'], 'userType' => 10, 'username' => $username, 'password' => $password, 'bazaarId' => $bazaarId,
		  'regionTarget' => $cookie, 'userStat' => $userStat, 'datatime' => date('Y-m-d H:i:s'), 'balance' => $balance, 'budget' => $budget, 'cost' => $cost,  'lastDatetime' => date('Y-m-d H:i:s') ]);
		return ['code'=>0, 'msg'=>'操作成功!'];
	}

	/**
	 * 删除数据
	 *
	 * @return
	 */
	public function delete(Request $request) {
		if($this->hasPermission($request->sessInfo, 'xhs:delete')) {
			return ['code'=> 403, 'msg'=> '你没有权限执行此操作!'];;
		}
		$param = $request->param();
		if( !isset($param['id']) ) {
			return ['code'=> 403, 'msg'=> '操作失败!'];
		}
		$explode = explode(',', $param['id']);
		foreach( $explode as $value ) {
			$username = Db::table('cfg_expand')->where('id', $value)->where('companyId', $request->sessInfo['companyId'])->value('username');
			if($username) {
				Db::table('cfg_xhs')->where('companyId', $request->sessInfo['companyId'])->where('username', $username)->delete();
			}
			Db::table('cfg_expand')->where('companyId', $request->sessInfo['companyId'])->where('id', $value)->delete();
		}
		return ['code'=> 0, 'msg'=> '删除成功!'];
	}

}
